<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>编辑器演示</title>
    <script src="images/jquery-2.1.1.min.js"></script>
    <script src="images/jquery.mloading.js"></script>
    <link rel="stylesheet" href="images/jquery.mloading.css">
    <style>
        .tox-notifications-container{z-index:2500;}
    </style>
</head>

<body>
<script src='tinymce.min.js'></script>

<script>
    tinymce.init({
        selector: '#content',
        language:'zh_CN',
        menubar: false,
        /*
        mobile: {
            menubar: true
        },
        */
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help  autosave indent2em autoresize formatpainter axupimgs importword',
        toolbar: 'fullscreen undo redo | selectall cut copy paste pastetext | fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough anchor | link unlink | formatselect alignleft aligncenter alignright alignjustify outdent indent | indent2em lineheight formatpainter |\
                 bullist numlist | blockquote subscript superscript removeformat | \
                 charmap hr insertdatetime |  table image axupimgs media | importword template | print preview | code',
        //width: 860, //编辑器高度
        min_height: 600,
        resize:true,
        /*content_css: [ //可设置编辑区内容展示的css，谨慎使用
            '/static/reset.css',
            '/static/ax.css',
            '/static/css.css',
        ],*/
        //保留style script标签
        //content_security_policy: "script-src *;",

        extended_valid_elements:'script[src],style[type],link[rel|href]', //允许的元素
        valid_children : '+div[style],+body[style|link]', //有效的子节点
        paste_webkit_styles: true, //允许粘贴样式

        forced_root_block:false,//强制根节点块元素
        allow_script_urls:true,//允许链接和图像url使用js
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;隶书=LiSu;楷体=KaiTi;黑体=SimHei,sans-serif;幼圆=YouYuan;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats',

        //importcss_append: true,
        //自定义文件选择器的回调内容
        file_picker_callback: function (callback, value, meta) {
            //文件分类
            var filetype='.pdf, .txt, .zip, .rar,.doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4,.png,.jpg,.jpeg,.gif';
            //后端接收上传文件的地址
            var upurl='editor/image';
            //为不同插件指定文件类型及后端地址
            switch(meta.filetype){
                case 'image':
                    filetype='.jpg, .jpeg, .png, .gif';
                    upurl='editor/image';
                    break;
                case 'media':
                    filetype='.mp3, .mp4';
                    upurl='editor/image';
                    break;
                case 'file':
                default:
            }

            //模拟出一个input用于添加本地文件
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', filetype);
            input.click();
            $(input).click(function() {
                this.blur();
                this.focus();
            });
            var i=0;
            $(input).on("change input",function() {
                i++;
                if(i==2) return;
                var file = this.files[0];

                formData = new FormData();
                formData.append('file', file, file.name );


                var xhr, formData;
                //console.log(file.name);
                $.ajax({
                    url:upurl,
                    type:"post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    beforeSend:function(){
                        $("body").mLoading();
                    },
                    success: function(json) {
                        if (!json || json.stat==0) {
                            //alert('上传失败: ' + json.msg);
                            tinymce.activeEditor.notificationManager.open({
                                text: json.msg,
                                type: 'error',
                                timeout: 3000
                            });
                            return;
                        }
                        tinymce.activeEditor.notificationManager.open({
                            text: json.msg,
                            type: 'success',
                            timeout: 3000
                        });
                        if (meta.filetype === 'file') {
                            callback(json.location, { text: file.name });
                        }
                        if (meta.filetype === 'image') {
                            callback(json.location, { alt: file.name });
                        }
                        if (meta.filetype === 'media') {
                            callback(json.location, { width:720 ,height:480,poster:'demo.jpg'});
                        }
                    },
                    complete:function(){
                        $("body").mLoading("hide");
                    },
                    error:function(data) {
                        tinymce.activeEditor.notificationManager.open({
                            text: '网络连接失败',
                            type: 'warning',
                            timeout: 3000
                        });
                    }
                });


            });



        },
        //为内容模板插件提供预置模板
        templates: [
            { title: '署名模板', description: '介绍文字1', content: '<div>模板内容</div><div style="float:right;margin:20px;clear:both;width:400px;text-align:center;">XXXXX公司综合部<br>2021年xx月xx日</div>' },
            { title: '模板2', description: '介绍文字2', content: '<div class="mceTmpl"><span class="cdate">CDATE</span>，<span class="mdate">MDATE</span>，我的内容</div>' }
        ],
        //
        template_cdate_format: '[CDATE: %m/%d/%Y : %H:%M:%S]',
        template_mdate_format: '[MDATE: %m/%d/%Y : %H:%M:%S]',
        autosave_ask_before_unload: false,
        //工具栏显示格式
        toolbar_mode : 'wrap',
        // images_upload_url: '/demo/upimg.php',
        // images_upload_base_path: '/demo',
        images_upload_handler: function (blobInfo, succFun, failFun) {
            var formData;
            var file = blobInfo.blob();//转化为易于理解的file对象
            formData = new FormData();
            formData.append('file', file, file.name );//此处与源文档不一样
            $.ajax({
                url:'editor/image',
                type:"post",
                data: formData,
                contentType: false,
                processData: false,
                beforeSend:function(){
                    $("body").mLoading();
                },
                success: function(json) {
                    if (!json || json.stat==0) {
                        //alert('上传失败: ' + json.msg);
                        //failFun("11");

                        $(".tox-dialog__busy-spinner").remove();
                        if(window.frames.length==2){
                            $(window.frames[1].document).find('#topbar .upall').text('全部上传');
                            $(window.frames[1].document).find('#file_list li.up-now').attr('class','up-no');
                        }
                        tinymce.activeEditor.notificationManager.open({
                            text: json.msg,
                            type: 'error',
                            timeout: 3000
                        });
                        return;
                    }
                    tinymce.activeEditor.notificationManager.open({
                        text: json.msg,
                        type: 'success',
                        timeout: 3000
                    });
                    succFun(json.location);


                },
                complete:function(){
                    $("body").mLoading("hide");
                },
                error:function(data) {
                    tinymce.activeEditor.notificationManager.open({
                        text: '网络连接失败',
                        type: 'warning',
                        timeout: 3000
                    });
                }
            });


        },
        //icons:'ax-color',
        branding: false,
        //powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
        //powerpaste_html_import: 'propmt',// propmt, merge, clear
        //powerpaste_allow_local_images: true,
    });

    function getHtml() {
        var html=tinyMCE.activeEditor.getContent();
        alert(html);
    }

    function getTxt() {

        var text=tinyMCE.activeEditor.getContent({'format': 'text'});
        alert(text);

    }
    var getFormatCode=function(strValue){
        return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
    }
</script>
<form method="post" style="margin:auto;" target="_blank" action="preview.jsp" >
    <button type="button" onclick="getHtml()">获取HTML内容</button><button type="button" onclick="getTxt()">获取TXT内容</button><button type="button" onclick="submit()">提交</button>
    <textarea id="content" name="content">Hello, World!</textarea>
</form>
<script>
    function submit(){
        document.getElementById("content")=tinyMCE.activeEditor.getContent();
        document.forms[0].submit();
    }
</script>

</body>

</html>